Clouds = class()
Clouds.height = 128
function Clouds:init(length,width,size)
    self.length = length
    self.width = width
    local xa = math.random()
    local ya = math.random() * math.random(20,2000)
    local base = 0.28
    self.clouds = {}
    for x = 1,length do
        self.clouds[x] = {}
        for y = 1,width do
            if (noise(xa + x * base,ya + y * base) + 1) < 0.7 then
                self.clouds[x][y] = true
            else
                self.clouds[x][y] = false
            end
        end
    end
    self.cloudSize = size
    self.t = Tesselator()
    self.t:setShader(shader("Project:CloudShader"))
        
    self.t:begin()
    local baseX = -self.length / 2
    for x = 1,self.length do
        for y = 1,self.width do
            local xa = (x - self.length / 2) * self.cloudSize + baseX
            local ya = (y - self.width / 2) * self.cloudSize
            if self.clouds[x][y] then
                self:renderCloud(self.t,xa,ya,x,y)
            end
        end
    end
    self.t:End()
    self.t.mesh.shader.RenderDistance = 400
end

function Clouds:render(eyePos)
    pushMatrix()
    translate(timer:getTime(),0,0)
    self.t.mesh.shader.EyePos = eyePos
    self.t.mesh.shader.GlobalColor = world.globalColor
    self.t:render()
    popMatrix()
end

function Clouds:renderCloud(t,x,y,xc,yc)
    local x0 = x
    local x1 = x + self.cloudSize
    local y0 = y
    local y1 = y + self.cloudSize
    
    local h0 = Clouds.height
    local h1 = h0 + 8
    
    t:color4b(210,210,205,255)
    
    t:vertex(x0, h0, y0)
    t:vertex(x1, h0, y0)
    t:vertex(x1, h0, y1)
    t:vertex(x1, h0, y1)
    t:vertex(x0, h0, y1)
    t:vertex(x0, h0, y0)
    
    t:vertex(x0, h1, y0)
    t:vertex(x1, h1, y0)
    t:vertex(x1, h1, y1)
    t:vertex(x1, h1, y1)
    t:vertex(x0, h1, y1)
    t:vertex(x0, h1, y0)
 
    t:color4b(245,245,240,255)
    if self:shouldRender(xc + 1,yc) then   
    t:vertex(x1, h0, y0)
    t:vertex(x1, h0, y1)
    t:vertex(x1, h1, y1)
    t:vertex(x1, h1, y1)
    t:vertex(x1, h1, y0)
    t:vertex(x1, h0, y0)
    end
    
    if self:shouldRender(xc - 1,yc) then
    t:vertex(x0, h0, y0)
    t:vertex(x0, h0, y1)
    t:vertex(x0, h1, y1)
    t:vertex(x0, h1, y1)
    t:vertex(x0, h1, y0)
    t:vertex(x0, h0, y0)
    end
    
    t:color4b(235,235,230,255)
    
    if self:shouldRender(xc,yc - 1) then
    t:vertex(x0, h0, y0)
    t:vertex(x1, h0, y0)
    t:vertex(x1, h1, y0)
    t:vertex(x1, h1, y0)
    t:vertex(x0, h1, y0)
    t:vertex(x0, h0, y0)
    end
    
    if self:shouldRender(xc,yc + 1) then
    t:vertex(x0, h0, y1)
    t:vertex(x1, h0, y1)
    t:vertex(x1, h1, y1)
    t:vertex(x1, h1, y1)
    t:vertex(x0, h1, y1)
    t:vertex(x0, h0, y1)
    end
end

function Clouds:shouldRender(x,y)
    if (x < 1) or (y < 1) or (x > self.length) or (y > self.width) then
        return true
    end
    return (not self.clouds[x][y])
end
